<?php

namespace app\modules\admin\services;

use app\common\services\BaseService;
use app\models\MerchantCategory;
use app\modules\admin\forms\category\MerchantCategoryForm;
use yii\helpers\ArrayHelper;

class MerchantCategoryService extends BaseService{

    /**
     * 创建
     * @param MerchantCategoryForm $form
     * @return bool
     * @throws \Throwable
     */
    public static function create(MerchantCategoryForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = new MerchantCategory();
        $model->setAttributes($form->getAttributes(),false);

        return $model->insert() !== false;
    }

    /**
     * 获取信息
     * @param $id
     * @return null|MerchantCategory
     */
    public static function getInfoById($id){
        return MerchantCategory::findOne(['cat_id'=>$id]);
    }

    /**
     * 获取信息
     * @param array $ids
     * @return MerchantCategory[]
     */
    public static function getInfoByIds(array $ids){
        return MerchantCategory::find()->where(['in','cat_id',$ids])->all();
    }

    /**
     * 更新
     * @param MerchantCategoryForm $form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function update(MerchantCategoryForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = MerchantCategory::findOne(['cat_id'=>$form->cat_id]);
        if(!$model){
            self::setError(\Yii::t("app","分类不存在"));
            return false;
        }

        $model->setAttributes($form->getAttributes(),false);
        return $model->update() !== false;
    }

    /**
     * 删除
     * @param $id
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function delete($id){
        $item = self::getList($id);
        $ids = ArrayHelper::getColumn($item,"cat_id");
        $ids[] = $id;
        if(empty($ids)){
            return;
        }
        MerchantCategory::deleteAll(['in','cat_id',$ids]);
    }

    /**
     * 返回列表(数组)
     * @param int $pid  父ID
     * @return array
     */
    public static function getList($pid=0)
    {
        $arr = MerchantCategory::find()->orderBy(['sort'=>SORT_ASC])->asArray()->all();
        return self::makeList($arr,$pid,0);
    }

    /**
     * 返回子列表
     * @param $arr
     * @param int $pid
     * @param int $level
     * @param int $curlevel
     * @param bool $clear
     * @return array
     */
    protected static function makeList($arr,$pid=0,$level=0)
    {
        static $child=[];

        foreach($arr as $k => $v)
        {
            if($v['parent_id']==$pid)
            {
                $v['level']=$level;
                $child[]=$v;
                unset($arr[$k]);
                self::makeList($arr,$v['cat_id'],$level+1);
            }
        }
        return $child;
    }
}